package com.shaozj.core.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;

import java.util.Collections;
import java.util.Map;

/**
 *  JPA 属性转换器： MAP < - > Jsonb
 *  自动在持久化和查询时进行序列化和反序列化
 */
public class JsonbConverter implements AttributeConverter<Map<String, Object>, String> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     *  Java --> 数据库序列化
     * @param attribute
     * @return
     */
    @Override
    public String convertToDatabaseColumn(Map<String, Object> attribute) {
        if (attribute == null || attribute.isEmpty()) {
            return "{}";
        }
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("JsonbConverter: JSON 序列化失败", e);
        }
    }


    /**
     * 数据库 -> Java 反序列化
     * @param dbData
     * @return
     */
    @Override
    public Map<String, Object> convertToEntityAttribute(String dbData) {
        if (dbData == null || dbData.trim().isEmpty()) {
            return Collections.emptyMap();
        }
        try {
            return objectMapper.readValue(dbData, Map.class);
        } catch (Exception e) {
            throw new IllegalArgumentException("JsonbConverter: JSON 反序列化失败", e);
        }
    }
}
